package com.qf.smsplatform.strategy.strategy.impl;

import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 路由策略
 * @author zjw
 */
@Service(value = "router")
@Slf4j
public class RouterStrategyImpl implements Strategy {

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("【策略模块-路由策略】  开始执行~~~~~~~~~~~~");
        String queueName = null;
        try {
            // 将submit再次作为消息发送到指定的队列中
            //1. 声明需要将当前消息发送到哪个队列中
            queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + submit.getGatewayID();
            //2. 创建队列 , 你也可以手动的在图形化界面中创建
            amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
            //3. 发送消息到待发Topic
            rabbitTemplate.convertAndSend(queueName,submit);
        } catch (AmqpException e) {
            PushErrorMessageUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            PushErrorMessageUtil.sendReport(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            log.error("【策略模块-路由策略】 发送消息到待发TOPIC失败   queueName = {} , ex = {}",queueName,e.getMessage());
            return false;
        }
        log.info("【策略模块-路由策略】  执行成功！！！！！！");
        return true;
    }
}
